package com.ray.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.google.appengine.api.search.query.QueryParser.item_return;
import com.qiniu.streaming.model.StreamListing;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.EmployeeDailyListBean;
import com.ray.bean.ExceptionDeclareBean;
import com.ray.bean.WeiXinPeopleBean;
import com.ray.mapper.EmployeeDailyListMapper;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.sun.mail.mbox.Mailbox;

import net.sf.json.JSONArray;

@Service
public class EmployeeDailyListService {

	@Autowired
	EmployeeDailyListMapper employeeDailyListMapper;
	@Autowired
	ScheduleService scheduleService;
	@Autowired
	WeiXinPeopleService weiXinPeopleService;
	@Autowired
	DingTalkService dingTalkService;

	/**
	 * @isUrl true
	 * jsonArray  数组集合
	 * orderId  系统编号
	 * companyOrderId 公司订单编号
	 * factoryId 工厂型号
	 * customerId 客户型号
	 * thing 工作内容/工序
	 * unitPrice 单价
	 * userId  报工人(选择人)
	 * useTime 用时
	 * count  数量
	 * @param map
	 * @return
	 *	Assert.isTrue(emp.getThing()!=null && !"".equals(emp.getThing()),"请输入工作内容/工序");
	 *	Assert.isTrue(emp.getUseTime()>0,"请输入大于0的工作时长");
	 *	Assert.isTrue(emp.getCount()>0,"请输入大于0的数量");
	 */
	public String  addEmployeeDailyNew(Map map) {
		StringUtil.checkIsTrue(map, "jsonArray", "未获取到参数");
		String dataArray=map.get("jsonArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(dataArray);
		List<EmployeeDailyListBean> list=(List<EmployeeDailyListBean>) JSONArray.toCollection(jsonArray, EmployeeDailyListBean.class);
		Assert.isTrue(list!=null && list.size()>0,"参数条数为0");
		list.forEach(emp->{
			emp.setId(StringUtil.getUUID());
			emp.setStatus(0);
		});
		map.put("employeeDailyList", list);
		int row = employeeDailyListMapper.addEmployeeDailyListNew(map);
		Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
		return ReturnStringUtil.ADD_SUCCESS;
	}

	/**
	 * @isUrl true 
	 * 获取员工日报表
	 * @param map
	 * @return
	 */
	public  DatatablesViewPageBean<EmployeeDailyListBean>  getEmployeeDailyNew(Map map){
		DatatablesViewPageBean<EmployeeDailyListBean> datatablesViewPageBean=new DatatablesViewPageBean<EmployeeDailyListBean>();
		List<EmployeeDailyListBean> dailyListBeans=employeeDailyListMapper.getEmployeeDailyNew(map);
		int  count=employeeDailyListMapper.getEmployeeDailyNewCount(map);
		datatablesViewPageBean.setReturnData(dailyListBeans);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		return datatablesViewPageBean;
	}
	
	/**
	 * @isUrl true
	 * jsonArray   json数组(包含id，status，unitPrice)
	 * id 
	 * status 状态 1 审核通过 2 审核不通过
	 * unitPrice 单价
	 * @param map
	 * @return
	 */
	public String approvalEmployeeDailyListNew(Map map) {
		String dataArray=map.get("jsonArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(dataArray);
		List<EmployeeDailyListBean> list=(List<EmployeeDailyListBean>) JSONArray.toCollection(jsonArray, EmployeeDailyListBean.class);
		
		//校验是否已经审核过了
		Set<String> idSet=list.stream().map(EmployeeDailyListBean::getId).collect(Collectors.toSet());
		Map paramMap=new HashMap();
		paramMap.put("idList", idSet);
		List<EmployeeDailyListBean> olDailyListBeans=employeeDailyListMapper.getEmployeeDailyNew(paramMap);
		olDailyListBeans.forEach(daily->{
			Assert.isTrue(daily.getStatus()==0,daily.getUserName()+":"+daily.getThing()+"已审核/已退回，不可再次操作");
		});
		
		
		
		Assert.isTrue(list.size()>0,"请选择审核项");
		map.put("list", list);
		int row = employeeDailyListMapper.approvalEmployeeDailyListNew(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		int status = list.get(0).getStatus();
		return status==1?ReturnStringUtil.APPROVAL_SUCCESS:ReturnStringUtil.RETURN_SUCCESS;
	}
	
	/**
	 * @isUrl true 
	 * id 
	 * 所有项  未修改则原样传回
	 * 当状态是  0 或者 2 的时候可修改
	 * @param map
	 * @return
	 */
	public String updateEmployeeDailyNew(Map map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id"); 
		
		//校验是否可修改
		Map paramMap=new HashMap();
		paramMap.put("id", map.get("id"));
		List<EmployeeDailyListBean> olDailyListBeans=employeeDailyListMapper.getEmployeeDailyNew(paramMap);
		olDailyListBeans.forEach(daily->{
			Assert.isTrue(daily.getStatus() != 1,"该记录审核已通过，不可修改");
		});
		
		int row = employeeDailyListMapper.updateEmployeeDailyListNew(map);
		Assert.isTrue(row>0,ReturnStringUtil.UPDATE_ERROR);
		return ReturnStringUtil.UPDATE_SUCCESS;
	}
	
	
	/**
	 * @isUrl true 
	 * id 
	 * 当状态是  0 或者 2 的时候可删除
	 * @param map
	 * @return
	 */
	public String deleteEmployeeDailyNew(Map map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id"); 
		
		//校验是否可修改
		Map paramMap=new HashMap();
		paramMap.put("id", map.get("id"));
		List<EmployeeDailyListBean> olDailyListBeans=employeeDailyListMapper.getEmployeeDailyNew(paramMap);
		olDailyListBeans.forEach(daily->{
			Assert.isTrue(daily.getStatus() != 1,"该记录审核已通过，不可删除");
		});
		
		int row = employeeDailyListMapper.deleteEmployeeDailyNew(map);
		Assert.isTrue(row>0,ReturnStringUtil.DELETE_ERROR);
		return ReturnStringUtil.DELETE_SUCCESS;
	}
	
	
	
	
/*****************************************************以下的都是旧方法*****************************************************/
	/**
	 * @isUrl true 
	 * 添加员工日报表数据
	 * @param dataArray(json字符串集合)
	 * @param thing(事情)
	 * @param useTime(所用时长)
	 */
	public String  addEmployeeDailyList(Map map) {
		Assert.notNull(map.get("dataArray"),"未获取到参数");
		String dataArray=map.get("dataArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(dataArray);
		List<EmployeeDailyListBean> list=(List<EmployeeDailyListBean>) JSONArray.toCollection(jsonArray, EmployeeDailyListBean.class);
	    Assert.isTrue(list!=null && list.size()>0,"参数条数为0");
		for(EmployeeDailyListBean emp:list) {
			emp.setId(StringUtil.getUUID());
			Assert.isTrue(emp.getThing()!=null && !"".equals(emp.getThing()),"请输入工作内容");
			Assert.isTrue(emp.getUseTime()>0,"请输入大于0的工作时长");
		}
		map.put("employeeDailyList", list);
		employeeDailyListMapper.addEmployeeDailyList(map);
		return ReturnStringUtil.ADD_SUCCESS;
	}


	/**
	 * @isUrl true
	 * 获取员工报表信息
	 * @param userId(用户id)
	 * @param startTime(开始时间)
	 * @param endTime(结束时间)
	 * @author nate
	 */
	public List<EmployeeDailyListBean> getEmployeeDailyList(Map map) {
		Assert.isTrue(map.get("startTime")!=null && !map.get("startTime").toString().equals(""),"未获取到开始时间");
		Assert.isTrue(map.get("endTime")!=null && !map.get("endTime").toString().equals(""),"未获到结束时间");
		List<EmployeeDailyListBean> employeeDailyList=employeeDailyListMapper.getEmployeeDailyList(map);
		return employeeDailyList;
	}


	
	/**
	 * @isUrl true
	 * 审核员工日报表信息
	 * @param userId(用户id)
	 * @param createTime(创建时间)
	 * @param status(状态 1 审核 2 退回)
	 * @author nate
	 */
	public String  approvalEmployeeDailyList(Map map) {
		Assert.isTrue(map.get("userId")!=null && !map.get("userId").toString().equals(""),"未获取到用户id");
		Assert.isTrue(map.get("createTime")!=null && !map.get("createTime").toString().equals(""),"未获取到用户时间");
		Assert.isTrue(checkApprovalEmployeeDailyList(map),"已审核或已退回,不可再次操作");;
		employeeDailyListMapper.approvalEmployeeDailyList(map);
		int status=Integer.parseInt(map.get("status").toString());
		return status==1?ReturnStringUtil.APPROVAL_SUCCESS:ReturnStringUtil.RETURN_SUCCESS;
	}

	/**
	 * 校验是否审核
	 * @param userId(用户id)
	 * @param createTime(创建时间)
	 * @author nate
	 */
	private boolean checkApprovalEmployeeDailyList(Map map) {
		boolean bool=false;
		List<String> idList=employeeDailyListMapper.checkApprovalEmployeeDailyList(map);
		if(idList==null|| idList.size()<=0) {
			bool=true;
		}
		return bool;
	}


	/**
	 * @isUrl true
	 * 删除员工日报表信息
	 * @param id(日报表id)
	 * @author nate
	 */
	public String  deleteEmployeeDailyList(Map map) {
		EmployeeDailyListBean employeeDailyListBean=employeeDailyListMapper.getEmployeeDailyListById(map.get("id").toString(),map.get("loginCompany").toString());
		Assert.notNull(employeeDailyListBean,"该记录不存在");
		Assert.isTrue(employeeDailyListBean.getStatus() != 1,"该记录已审核不可删除");
		employeeDailyListMapper.deleteEmployeeDailyListById(map.get("id").toString());
		return  ReturnStringUtil.DELETE_SUCCESS;
	}

	
	/**
	 * @isUrl true 
	 * 修改员工日报表信息
	 * @param id(日报表id)
	 * @param thing(日报表id)
	 * @param useTime(日报表id)
	 * @author nate
	 */
	public String  updateEmployeeDailyList(Map map) {
		Assert.isTrue(map.get("id")!=null && !map.get("id").toString().equals(""),"未获取到id");
		Assert.isTrue(map.get("thing")!=null && !map.get("thing").toString().equals(""),"未获取到工作内容");
		Assert.isTrue(map.get("useTime")!=null && !map.get("useTime").toString().equals(""),"未获取到工作时长");
		EmployeeDailyListBean employeeDailyListBean=employeeDailyListMapper.getEmployeeDailyListById(map.get("id").toString(),map.get("loginCompany").toString());
		Assert.notNull(employeeDailyListBean,"该记录不存在");
		Assert.isTrue(employeeDailyListBean.getStatus() != 1,"该记录已审核不可修改");
		map.put("userId", employeeDailyListBean.getUserId());
		map.put("createTime", employeeDailyListBean.getCreateTime());
		employeeDailyListMapper.updateEmployeeDailyList(map);
		return ReturnStringUtil.UPDATE_SUCCESS;
	}
	
	
	/**
	 * 获取员工日报表合计数据
	 * @param map
	 * @return
	 */
	public Map getEmployeeDailyTotal(Map map) {
		return employeeDailyListMapper.getEmployeeDailyTotal(map);
	}
	
	/**
	 * 获取异常申类型
	 * @return
	 */
	public List<ExceptionDeclareBean> getExceptionType(Map map){
		return employeeDailyListMapper.getExceptionType(map);
	}
	
	/**
	 * 添加异常类型
	 * exceptionType 异常类型
	 * @param map
	 * @return
	 */
	public String addExceptionType(Map map) {
		StringUtil.checkIsTrue(map, "exceptionType", "未获取到异常类型");
		List<ExceptionDeclareBean> list = this.getExceptionType(map);
		Set<String> set = list.stream().map(ExceptionDeclareBean::getExceptionType).collect(Collectors.toSet());
		Assert.isTrue(!set.contains(map.get("exceptionType").toString()),"该异常类型已存在");
		int row = employeeDailyListMapper.addExceptionType(map);
		Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
	    return ReturnStringUtil.ADD_SUCCESS;
	}
	
	/**
	 * 修改异常类型  禁用或者使用
	 * @param map
	 * @return
	 */
	public String updateExceptionType(Map map) {
		StringUtil.checkIsTrue(map, "id","未获取到id");
		StringUtil.checkIsTrue(map, "status","未获取到状态");
		int row  = employeeDailyListMapper.updateExceptionType(map);
		return ReturnStringUtil.UPDATE_SUCCESS;
	}
	
	/**
	 * typeId  异常类型id 
	 * exceptionType 异常类型描述 
	 * img1 
	 * img2
	 * img3
	 * img4
	 * notifyUser 知会人
	 * 添加异常申报单
	 */
	public  Map addExceptionDeclare(Map map) {
		Map<String,String> retunMap = new HashMap();
		StringUtil.checkIsTrue(map, "typeId", "未获取到类型id");
		StringUtil.checkIsTrue(map, "exceptionType", "未获取到类型描述");
		StringUtil.checkNotNull(map, "img1", "未获取到图片1");
		StringUtil.checkNotNull(map, "img2", "未获取到图片2");
		StringUtil.checkNotNull(map, "img3", "未获取到图片3");
		StringUtil.checkNotNull(map, "img4", "未获取到图片4");
		StringUtil.checkIsTrue(map, "notifyUser", "未获取到知会人");
		SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString= simpleDateFormat.format(new Date());
		int row = employeeDailyListMapper.addExceptionDeclare(map);
		map.put("handOverUser", map.get("notifyUser"));
		//保存发起记录
		int addRow = employeeDailyListMapper.addHandOverRecord(map);
		//发送消息给知会人
		List<WeiXinPeopleBean> list = weiXinPeopleService.getWexinPeopleByUserId(map.get("notifyUser").toString());
		String mString = "";
		if(list.size()<=0) {
			mString =" 知会人未关联微信,请另行通知";
		}else {
			scheduleService.sendMessageUtilByOpenId("有一个新的异常指派给您解决", list.get(0), map.get("ecxeptionType").toString(), dateString, "新增异常单", "phoneApp/exceptionDetail?id="+map.get("id").toString());
		}
		Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
		retunMap.put("returnStr", ReturnStringUtil.ADD_SUCCESS+mString);
		retunMap.put("returnId", map.get("id").toString());
		return retunMap;
	}
	
	
	/**
	 * 获取异常申报信息
	 * @param map
	 * @return
	 */
	private List<ExceptionDeclareBean> getExceptionDeclareList(Map map){
		return employeeDailyListMapper.getExceptionDeclare(map);
	}
    public DatatablesViewPageBean<ExceptionDeclareBean> getExceptionDeclare(Map map){
    	DatatablesViewPageBean<ExceptionDeclareBean> datatablesViewPageBean = new DatatablesViewPageBean<ExceptionDeclareBean>();
    	List<ExceptionDeclareBean> list = this.getExceptionDeclareList(map);
    	int count = employeeDailyListMapper.getExceptionDeclareCount(map);
    	datatablesViewPageBean.setReturnData(list);
    	datatablesViewPageBean.setiTotalRecords(count);
    	datatablesViewPageBean.setiTotalDisplayRecords(count);
    	return datatablesViewPageBean;
    }
    
    /**
     * id 
     * handOverUser 转交人id
     * 转交异常申报单
     */
	public String handOverException(Map map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id");
		StringUtil.checkIsTrue(map, "handOverUser", "未获取到转交人");
		List<ExceptionDeclareBean> list = this.getExceptionDeclareList(map);
		Assert.isTrue(list.size()>0,"该异常申报信息不存在");
		ExceptionDeclareBean exceptionDeclareBean = list.get(0);
		Assert.isTrue(exceptionDeclareBean.getStatus() != 1,"该记录已完成，不可转交");
		int row = employeeDailyListMapper.handOverException(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		int addRow = employeeDailyListMapper.addHandOverRecord(map);
		//发消息给被转交人
		SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString= simpleDateFormat.format(new Date());
		List<WeiXinPeopleBean> listtt = weiXinPeopleService.getWexinPeopleByUserId(map.get("handOverUser").toString());
		String mString = "";
		if(listtt.size()<=0) {
			mString =" 转交接收人未关联微信,请另行通知";
		}else {
		    scheduleService.sendMessageUtilByOpenId("有一个新的异常转交给您解决", listtt.get(0), map.get("ecxeptionType").toString(), dateString, "转交异常单", "");
		}
		return ReturnStringUtil.OPERATION_SUCCESS + mString;
	}
	
	/**
	 * 解决异常类型申报单
	 * id 
	 * solveMethod 解决方式
	 * @param map
	 * @return
	 */
	public String endOverException(Map map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id");
		StringUtil.checkIsTrue(map, "solveMethod", "未获取到解决方式");
		List<ExceptionDeclareBean> list = this.getExceptionDeclareList(map);
		Assert.isTrue(list.size()>0,"该异常申报信息不存在");
		ExceptionDeclareBean exceptionDeclareBean = list.get(0);
		Assert.isTrue(exceptionDeclareBean.getStatus() != 1,"该记录已完成");
		int row = employeeDailyListMapper.endOverException(map);
		//发消息给被发起人
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}
	
	/**
	 * 解决异常类型复期
	 * id 
	 * answerDate 复期
	 * @param map
	 * @return
	 */
	public String setAnswerDate(Map map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id");
		StringUtil.checkIsTrue(map, "answerDate", "未获取到复期");
		List<ExceptionDeclareBean> list = this.getExceptionDeclareList(map);
		Assert.isTrue(list.size()>0,"该异常申报信息不存在");
		ExceptionDeclareBean exceptionDeclareBean = list.get(0);
		Assert.isTrue(exceptionDeclareBean.getStatus() != 1,"该记录已完成");
		int row = employeeDailyListMapper.setAnswerDate(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}
	
	/**
	 * 审核转交记录
	 * id  
	 * notifyStatus 同意 1 不同意 2
	 * @param map
	 * @return
	 */
	public String approvalHandOver(Map map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id");
		StringUtil.checkIsTrue(map, "notifyStatus", "未获取到是否同意");
		int notifyStatus  = Integer.parseInt(map.get("notifyStatus").toString());
		map.remove("notifyStatus");
		List<ExceptionDeclareBean> list = this.getExceptionDeclareList(map);
		Assert.isTrue(list.size()>0,"该异常申报信息不存在");
		ExceptionDeclareBean exceptionDeclareBean = list.get(0);
		Assert.isTrue(exceptionDeclareBean.getStatus() != 1,"该记录已完成");
		int row = 0;
		map.put("notifyStatus", notifyStatus);
		if(notifyStatus==2) {
			row = employeeDailyListMapper.returnHandOver(map);
		}
		if(notifyStatus==1) {
			row = employeeDailyListMapper.agreeHandOver(map);
		}
		map.put("handOverUser", exceptionDeclareBean.getNotifyUser());
		int addRow = employeeDailyListMapper.addHandOverRecord(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		String errorMsg = "";
		List<WeiXinPeopleBean> weiXinPeopleBeans =  weiXinPeopleService.getWexinPeopleByUserId(exceptionDeclareBean.getNotifyUser());
		if (weiXinPeopleBeans.size()<=0) {
			errorMsg = " 转交发起人未关联微信，请人工通知";
		}else {
			dingTalkService.sendApplyStatusTips("异常转交审核通知", exceptionDeclareBean.getNotifyUser(), notifyStatus+"", map.get("loginUserName").toString(), "");
		}
		//发消息给被转交人
		return ReturnStringUtil.OPERATION_SUCCESS + errorMsg;
	}

}
